package com.etc.dao;

import com.etc.entity.Book;
import com.etc.utils.DruidUtils;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author kalista
 * @Description
 * @Date 2020/12/11  11:38
 **/
public class BookDao {

    /**
     * 查看所有书籍
     * @return
     */
    public List<Book> getBooks() throws SQLException {
        List<Book> books = new ArrayList<>();
        Statement statement = DruidUtils.getConnection().createStatement();
        ResultSet resultSet = statement.executeQuery("select * from book");
        while (resultSet.next()){
            Book book = new Book();
            book.setId(resultSet.getInt("id"));
            book.setName(resultSet.getString("name"));
            books.add(book);
        }
        return books;
    }


    /**
     * 根据id进行删除
     * @param id
     * @return
     */
    public int deleteById(Integer id) throws SQLException {
        String sql = "delete from book where id = ?";
        PreparedStatement ps = DruidUtils.getConnection().prepareStatement(sql);
        ps.setInt(1,id);
        return ps.executeUpdate();
    }



    /**
     * 根据id进行删除
     * @param
     * @return
     */
    public int add(String name,String pice) throws SQLException {
        String sql = "insert into book(name,pice,status) value(?,?,1)";
        PreparedStatement ps = DruidUtils.getConnection().prepareStatement(sql);
        ps.setString(1,name);
        ps.setString(2,pice);
        return ps.executeUpdate();
    }



    /**
     * 根据id进行删除
     * @param id
     * @return
     */
    public Book getBook(Integer id) throws SQLException {
        Book book = null;
        String sql = "select * from book where id = ?";
        PreparedStatement ps = DruidUtils.getConnection().prepareStatement(sql);
        ps.setInt(1,id);
        ResultSet resultSet = ps.executeQuery();
        while (resultSet.next()){
            book =  new Book();
            book.setId(resultSet.getInt("id"));
            book.setName(resultSet.getString("name"));
            book.setPice(resultSet.getString("pice"));
            book.setStatus(resultSet.getInt("status"));
        }
        return book;
    }



    /**
     * 更新
     * @param id
     * @return
     */
    public int update(String id,String name,String pice,String status) throws SQLException {
        String sql = "update book set name=?,pice=?,status=? where id = ?";
        PreparedStatement ps = DruidUtils.getConnection().prepareStatement(sql);
        ps.setString(1,name);
        ps.setString(2,pice);
        ps.setInt(3,Integer.valueOf(status));
        ps.setInt(4,Integer.valueOf(id));
        return ps.executeUpdate();
    }

}
